/*
 * Copyright (c) 2015. kupat Corporation. All rights reserved.
 *  see statement on http://www.kupat.cn.
 */
package com.kfgj.hkp.common.components.stock;

import com.kfgj.hkp.common.components.http.HttpHelper;
import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.NameValuePair;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by liwensihan on 2015/1/12.
 *
 * @author liwensihan
 */
public class StockSinaUtils {

    private static String url = "http://hq.sinajs.cn/list=";

    public static List<StockInfo> queryStock(String[] codes) {

        String cs = "";
        for (int i = 0; i < codes.length; i++) {
            if (i == codes.length - 1) {
                cs += codes[i];
            } else {
                cs += codes[i] + ",";
            }
        }

        List<StockInfo> stockInfos = new ArrayList<StockInfo>();
        try {
            String res = HttpHelper.getRequest(url + cs);
            String[] stocks = res.split(";");

            for (String st : stocks) {
                String[] sts = st.split("=");
                if (sts.length < 2 || sts[1].equals("\"\"")) {
                    continue;
                }
                sts = sts[1].substring(1, sts[1].length() - 1).split(",");
                StockInfo info = new StockInfo();
                info.setStockName(sts[0]);
                info.setTodayStartPrice(BigDecimal.valueOf(Double.parseDouble(sts[1])));
                info.setYesTodayEndPrice(BigDecimal.valueOf(Double.parseDouble(sts[2])));
                info.setCurrentPrice(BigDecimal.valueOf(Double.parseDouble(sts[3])));
                info.setTodayMaxPrice(BigDecimal.valueOf(Double.parseDouble(sts[4])));
                info.setTodayMinPrice(BigDecimal.valueOf(Double.parseDouble(sts[5])));
                stockInfos.add(info);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

        }
        return stockInfos;
    }

    public static StockInfo queryStock(String code) {
        List<StockInfo> stocks = queryStock(new String[]{code});
        return stocks.size() > 0 ? stocks.get(0) : null;
    }

    public static String getCharset(Header header, String def) {
        HeaderElement[] hes = header.getElements();
        for (int i = 0; i < hes.length; i++) {
            System.out.println(hes[i]);
            HeaderElement he = hes[i];
            NameValuePair[] nvps = he.getParameters();
            for (int j = 0; j < nvps.length; j++) {
                NameValuePair nvp = nvps[j];
                if ("charset".equalsIgnoreCase(nvp.getName())) {
                    return nvp.getValue();
                }
            }
        }
        return def;
    }

    public static void main(String[] args) {
        System.out.println("===" + StockSinaUtils.queryStock("sh002564"));
        System.out.println("===" + StockSinaUtils.queryStock("sz002564"));
    }
}
